//
//  WelcomeViewController.swift
//  Super_WeiBo
//
//  Created by SuperMac on 16/3/23.
//  Copyright © 2016年 lc. All rights reserved.
//

import UIKit
import SDWebImage

class WelcomeViewController: UIViewController {

    /// 保存底部约束
    var bottomCons: NSLayoutConstraint?
    
    override func viewDidLoad() {
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        // 添加子控件
        view.addSubview(backImg)
        view.addSubview(iconView)
        view.addSubview(messageLabel)
        // 布局子控件
        backImg.xmg_Fill(view)
        // 头像约束
        let cons = iconView.xmg_AlignInner(type: XMG_AlignType.BottomCenter, referView: view, size: CGSize(width: 100, height: 100), offset: CGPoint(x: 0, y: -150))
        // 拿到头像的底部约束
        bottomCons = iconView.xmg_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        // 文本约束
        messageLabel.xmg_AlignVertical(type: XMG_AlignType.BottomCenter, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 20))
        
        // 设置头像
        if let iconUrl = UserAccount.loadAccount()?.avatar_large
        {
            let url = NSURL(string: iconUrl)!
            iconView.sd_setImageWithURL(url)
        }
    }
    
    // UI完全展示后再进行动画
    override func viewDidAppear(animated: Bool) 
    {
        super.viewDidAppear(animated)
        
        // 改变头像的底部约束
        bottomCons?.constant = -UIScreen.mainScreen().bounds.height -  bottomCons!.constant
        
        // 执行动画
        UIView.animateWithDuration(2.0, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            // 头像动画
            self.iconView.layoutIfNeeded()
            }) { (_) -> Void in
                
                // 文本动画
                UIView.animateWithDuration( 2.0, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.messageLabel.alpha = 1.0
                    }, completion: { (_) -> Void in
                        // 完全展示后 进入主页
                        NSNotificationCenter.defaultCenter().postNotificationName(Super_ChaoSwitchRootControllerKey, object: true)
                })
        }
    }
    
    // MARK: - 懒加载
    /// 背景图
    private lazy var backImg = UIImageView(image: UIImage(named: "ad_background"))
    /// 头像
    private lazy var iconView : UIImageView = {
       let iv = UIImageView(image: UIImage(named: "avatar_default_big"))
        iv.layer.cornerRadius = 50
        iv.clipsToBounds = true
        return iv
    }()
    /// 文本
    private lazy var messageLabel : UILabel = {
       let l = UILabel()
        l.text = "欢迎回来"
        l.sizeToFit()
        l.alpha = 0.0
        return l
    }()
    
}
